<template>
  <div>
    <searchBox @searchChange = "searchChange" />
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="topicList"
        row-key="ID"
        border
        @sort-change= "dataSort" 
      >
        <el-table-column
        width="65px"
          align="left"
          label="ID"
          prop="id"
        />
        <el-table-column
        width="100px"
          align="left"
          label="话题"
          prop="title"
          show-overflow-tooltip = true
        />
        <el-table-column
        width="155px"
          align="left"
          label="创建时间"
          prop="createTime"
        />
        <el-table-column
          align="left"
          label="评论数"
          prop="comment"
          width="93px"
          sortable
          :sort-method="(a,b)=>{return a._comment - b._comment}"
        />
        <el-table-column
          align="left"
          label="点赞数"
          prop="digg"
          width="93px"
          sortable
          :sort-method="(a,b)=>{return a._digg - b._digg}"
        />
        <el-table-column
          align="left"
          label="分享数"
          prop="share"
          width="93px"
          sortable
          :sort-method="(a,b)=>{return a._share - b._share}"
        />
        <el-table-column
          align="left"
          label="收藏数"
          prop="collect"
          width="93px"
          sortable
          :sort-method="(a,b)=>{return a._collect - b._collect}"
        />
        <el-table-column
          align="left"
          label="次增评论"
          prop="comment1"
          width="105px"
          sortable
          :sort-method="(a,b)=>{return a._comment1 - b._comment1}"
        />
        <el-table-column
          align="left"
          label="次增点赞"
          prop="digg1"
          width="105px"
          sortable
          :sort-method="(a,b)=>{return a._digg1 - b._digg1}"
        />
        <el-table-column
          align="left"
          label="次增分享"
          prop="share1"
          width="105px"
          sortable
          :sort-method="(a,b)=>{return a._share1 - b._share1}"
        />
        <el-table-column
          align="left"
          label="次增收藏"
          prop="collect1"
          width="105px"
          sortable
          :sort-method="(a,b)=>{return a._collect1 - b._collect1}"
        />
        <el-table-column
          align="left"
          label="3增评论"
          prop="comment3"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._comment3 - b._comment3}"
        />
        <el-table-column
          align="left"
          label="3增点赞"
          prop="digg3"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._digg3 - b._digg3}"
        />
        <el-table-column
          align="left"
          label="3增分享"
          prop="share3"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._share3 - b._share3}"
        />
        <el-table-column
          align="left"
          label="3增收藏"
          prop="collect3"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._collect3 - b._collect3}"
        />
        <el-table-column
          align="left"
          label="7增评论"
          prop="comment7"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._comment7 - b._comment7}"
        />
        <el-table-column
          align="left"
          label="7增点赞"
          prop="digg7"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._digg7 - b._digg7}"
        />
        <el-table-column
          align="left"
          label="7增分享"
          prop="share7"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._share7 - b._share7}"
        />
        <el-table-column
          align="left"
          label="7增收藏"
          prop="collect7"
          width="100px"
          sortable
          :sort-method="(a,b)=>{return a._collect7 - b._collect7}"
        />
        <el-table-column
          align="left"
          label="采集状态"
          prop="statusString"
          width="85px"
        />
        <el-table-column
          align="left"
          label="操作"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="openUrl(scope.row.url)"
            >观看视频</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
      </div>
</template>

<script setup>
import {
  createQmGameList,
  deleteQmGameList,
  deleteQmGameListByIds,
  updateQmGameList,
  findQmGameList,
  getQmGameListList
} from '@/api/qmGameList'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import searchBox from '../../components/search/searchBox.vue';
import { useRouter, useRoute } from 'vue-router'

import {
  getHugeList
} from '@/api/openApi'

defineOptions({
  name: 'QmDataList'
})


const router = useRouter()
const route = useRoute()

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  name: '',
})



const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTopicList()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTopicList()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTopicList()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTopicList()
}

// 查询
var searchChange = function(date){
  searchInfo.value = date
  getTopicList()
}

var order = ""

var dataSort = function(column){
  if (column.order == null){
    order = ""
    getTopicList()
  } else {
    order = (column.order == 'ascending') ? column.prop + ' asc' : column.prop + ' desc' ;
    getHugeList({ type: 'collectDetailList', add_params: order,page: 1,params:route.query.collectId ,...searchInfo.value}).then(res => {
      if (res.code === 0) {
        topicList.value = []
        res.data.list.forEach(item => {
          const value = JSON.parse(item.response)

          const publishDate = value.createTime.split(' ')[0]

          value._comment = value.comment
          value._share = value.share
          value._collect = value.collect
          value._digg = value.digg
          value._comment1 = value.comment1
          value._share1 = value.share1
          value._collect1 = value.collect1
          value._digg1 = value.digg1
          value._comment3 = value.comment3
          value._share3 = value.share3
          value._collect3 = value.collect3
          value._digg3 = value.digg3
          value._comment7 = value.comment7
          value._share7 = value.share7
          value._collect7 = value.collect7
          value._digg7 = value.digg7
          if (publishDate <= date2){
            value.comment1 = addCommas(value.comment1)
            value.share1 = addCommas(value.share1)
            value.collect1 = addCommas(value.collect1)
            value.digg1 = addCommas(value.digg1)
          }else{
            value.comment1 = "-"
            value.share1 = "-"
            value.collect1 = "-"
            value.digg1 = "-"
          }

          if (publishDate <= date3){
            value.comment3 = addCommas(value.comment3)
            value.share3 = addCommas(value.share3)
            value.collect3 = addCommas(value.collect3)
            value.digg3 = addCommas(value.digg3)
          }else{
            value.comment3 = "-"
            value.share3 = "-"
            value.collect3 = "-"
            value.digg3 = "-"
          }
          if (publishDate <= date7){
            value.comment7 = addCommas(value.comment7)
            value.share7 = addCommas(value.share7)
            value.collect7 = addCommas(value.collect7)
            value.digg7 = addCommas(value.digg7)
          }else{
            value.comment7 = "-"
            value.share7 = "-"
            value.collect7 = "-"
            value.digg7 = "-"
          }

          topicList.value.push(value)
        })
        total.value = res.data.total
        page.value = res.data.page
      }
    })
  }
}

const date = new Date()

date.setDate(date.getDate() - 1)
const date1 = date.toISOString().split('T')[0]; 
const yesterDaySearchDate = {start_date:date1,end_date:date1}
date.setDate(date.getDate() - 1)
const date2 = date.toISOString().split('T')[0]; 
date.setDate(date.getDate() - 1)
const date3 = date.toISOString().split('T')[0]; 
date.setDate(date.getDate() - 4)
const date7 = date.toISOString().split('T')[0];


const topicList = ref([])
const getTopicList = () => {
  
  getHugeList({ type: 'collectDetailList',add_params: order, page: page.value,params:route.query.collectId ,...searchInfo.value}).then(res => {
    if (res.code === 0) {
      topicList.value = []
      res.data.list.forEach(item => {
        const value = JSON.parse(item.response)
         
        const publishDate = value.createTime.split(' ')[0]
        value._comment = value.comment
        value._share = value.share
        value._collect = value.collect
        value._digg = value.digg
        value._comment1 = value.comment1
        value._share1 = value.share1
        value._collect1 = value.collect1
        value._digg1 = value.digg1
        value._comment3 = value.comment3
        value._share3 = value.share3
        value._collect3 = value.collect3
        value._digg3 = value.digg3
        value._comment7 = value.comment7
        value._share7 = value.share7
        value._collect7 = value.collect7
        value._digg7 = value.digg7
        if (publishDate <= date2){
          value.comment1 = addCommas(value.comment1)
          value.share1 = addCommas(value.share1)
          value.collect1 = addCommas(value.collect1)
          value.digg1 = addCommas(value.digg1)
        }else{
          value.comment1 = "-"
          value.share1 = "-"
          value.collect1 = "-"
          value.digg1 = "-"
        }

        if (publishDate <= date3){
          value.comment3 = addCommas(value.comment3)
          value.share3 = addCommas(value.share3)
          value.collect3 = addCommas(value.collect3)
          value.digg3 = addCommas(value.digg3)
        }else{
          value.comment3 = "-"
          value.share3 = "-"
          value.collect3 = "-"
          value.digg3 = "-"
        }
        if (publishDate <= date7){
          value.comment7 = addCommas(value.comment7)
          value.share7 = addCommas(value.share7)
          value.collect7 = addCommas(value.collect7)
          value.digg7 = addCommas(value.digg7)
        }else{
          value.comment7 = "-"
          value.share7 = "-"
          value.collect7 = "-"
          value.digg7 = "-"
        }



        topicList.value.push(value)
      })
      total.value = res.data.total
      page.value = res.data.page
    }
  })
}

// ============== 表格控制部分结束 ===============
const platformOptions = ref([])
// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  platformOptions.value = await getDictFunc('platform')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteQmGameListFunc(row)
  })
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
  const IDs = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
        multipleSelection.value.map(item => {
          IDs.push(item.ID)
        })
  const res = await deleteQmGameListByIds({ IDs })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === IDs.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTopicList()
  }
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const getDetails = async(row) => {
  router.push({ name: 'collectListDetail', query: {listId: row.id}})
}


const openUrl = async(url) => {
  window.open(url,"_blank")
}

// 删除行
const deleteQmGameListFunc = async(row) => {
  const res = await deleteQmGameList({ ID: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

function addCommas(value) {
  // ①如下方法：处理千分位并保留两位小数
  // return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  // ②如下方法：将整数位处理成千分位，小数位不变
  const parts = String(value).split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return parts.join('.')
}

  

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
    appid: '',
    secret: '',
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return

    let res
    switch (type.value) {
      case 'create':
        res = await createQmGameList(formData.value)
        break
      case 'update':
        res = await updateQmGameList(formData.value)
        break
      default:
        res = await createQmGameList(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

</script>

<style>

</style>
